package com.bwie.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @Author zhaohaoyang
 * @Create 2025/5/21 13:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/user/index")
@Slf4j
public class IndexController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    TbUserService tbUserService;


    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginVo loginVo){
        log.info("进入index方法");
        //1.判断用户是否存在
        TbUser tbUser = tbUserService.getOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if(tbUser==null){
            return Result.error().setMsg("用户名不存在");
        }
        //2.判断密码是否正确
        //密码加密
        String hash = DigestUtil.md5Hex(loginVo.getUserPass());
        log.info("加密密码:"+hash);
        if(!hash.equals(tbUser.getUserPass())){
            return Result.error().setMsg("密码错误");
        }
        //3.生成token并存入缓存
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName()).compact();
        String key = "token-"+tbUser.getUserId();
        redisTemplate.opsForValue().set(key,token,60, TimeUnit.MINUTES);
        //4.返回用户信息以及token
        tbUser.setUserPass(null);
        tbUser.setToken(token);
        return Result.ok().setData(tbUser);
    }

    /**
     * 获取菜单树
     * @return
     */
    @PostMapping("/getMenuTree")
    public Result getMenuTree(HttpServletRequest request){
        //1.获取token并解析用户ID
        String token = request.getHeader("token");
        if(token==null){
            return Result.error().setMsg("请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        //2.根据用户菜单返回
       List<TbMenu> menuTree =  tbUserService.getMenuTree(userId);
        //3.返回用户菜单树
        return Result.ok().setData(menuTree);
    }

    /**
     * 分页查询商户列表
     * @param pageUserVo
     * @return
     */
    @PostMapping("/getUserList")
    public Result getUserList(@RequestBody PageUserVo pageUserVo){
        return tbUserService.getUserList(pageUserVo);
    }

    /**
     * 用户修改
     * @param tbUser
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody TbUser tbUser){
        return tbUserService.updateUser(tbUser);
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestPart MultipartFile file){
        return tbUserService.uploadFile(file);
    }

    /**
     *用户删除
     * @param id
     * @return
     */
    @PostMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        return tbUserService.deleteById(id);
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<TbUser> userList){
        return tbUserService.deleteBatch(userList);
    }

    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody TbUser tbUser){
        return tbUserService.checkUser(tbUser);
    }
}
